package com.daiyang.blog.common.interceptor;

import com.daiyang.blog.common.utils.JWTUtils;
import io.jsonwebtoken.Claims;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String jwt = request.getHeader("user_token");
        log.info("jwt:{}", jwt);
        Claims claims = (Claims) JWTUtils.parseToken(jwt); // 这里无论是否解析成功都会进入错误逻辑

        // 矛盾点：当claims为null时反而返回true
        if(claims != null){
            log.info("令牌验证成功");
            return true; // 这里应该拒绝请求
        }
        response.setStatus(401);
        return false; // 这里应该允许通过
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {



    }
}
